package com.qf.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

//@Component
@Configuration //标识这是一个配置类
@PropertySource("classpath:jdbc.properties")
public class MyBatisConfig {

    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean
    public PlatformTransactionManager ptm(DataSource ds){
        DataSourceTransactionManager ptm = new DataSourceTransactionManager();
        ptm.setDataSource(ds);
        return ptm;
    }

    @Bean
    public DataSource ds(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean ssfb(DataSource ds){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setDataSource(ds);

        org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
        //日志输出
        config.setLogImpl(StdOutImpl.class);

        //开启驼峰命名
        config.setMapUnderscoreToCamelCase(true);
        ssfb.setConfiguration(config);

        return ssfb;
    }

    @Bean
    public static MapperScannerConfigurer msc(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();

        msc.setBasePackage("com.qf.mapper");

        return msc;
    }
}
